<?php

namespace app\aliyun\controller;

use app\common\controller\Aliyun;
use app\common\lib\Aes;
use Sts\Request\V20150401\AssumeRoleRequest;

class AliyunVOD
{
    /**
     * 获取视频临时token值
     * @return string
     */
    public function getStsToken(string $sessionName, int $durationSeconds)
    {
        $roleArn = 'acs:ram::1919834008307914:role/vodrole';
        try
        {
            $AilynInstance = Aliyun::getVodInstance();
            $request = new AssumeRoleRequest();
            $request->setRoleSessionName($sessionName);
            $request->setRoleArn($roleArn);
            $request->setDurationSeconds($durationSeconds);
            $response = $AilynInstance->getAcsResponse($request);

            $responseArray = json_decode(json_encode($response), true);

            $data = [
                'AccessKeySecret' => $responseArray['Credentials']['AccessKeySecret'],
                'AccessKeyId' => $responseArray['Credentials']['AccessKeyId'],
                'Expiration' => $responseArray['Credentials']['Expiration'],
                'SecurityToken' => $responseArray['Credentials']['SecurityToken'],
            ];

            $data = json_encode($data, true);

            return (new Aes())->encryptWithOpenssl($data);
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return '';
        }
    }

    /**
     * 获取视频临时token值
     * @return string
     */
    public function getStsTokenZyhs(string $sessionName, int $durationSeconds)
    {
        $roleArn = 'acs:ram::1919834008307914:role/vodrole';
        try
        {
            $AilynInstance = Aliyun::getVodInstance();
            $request = new AssumeRoleRequest();
            $request->setRoleSessionName($sessionName);
            $request->setRoleArn($roleArn);
            $request->setDurationSeconds($durationSeconds);
            $response = $AilynInstance->getAcsResponse($request);

            $responseArray = json_decode(json_encode($response), true);

            $data = [
                'AccessKeySecret' => $responseArray['Credentials']['AccessKeySecret'],
                'AccessKeyId' => $responseArray['Credentials']['AccessKeyId'],
                'Expiration' => $responseArray['Credentials']['Expiration'],
                'SecurityToken' => $responseArray['Credentials']['SecurityToken'],
            ];

            $data = json_encode($data, true);

            return (new Aes())->encryptWithOpenssl($data, 'zyhsapp');
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return '';
        }
    }
}